#!/usr/bin/python

import sys
import os
import re
import logging as log
from testUnit import tester as T
from mount import mount as mon

class rabbitmq_installer():
    def __init__(self):
        pass

    def mount(self,ips,dev):
        if dev['mq-device']:
            for ip in ips:
                os.system('ssh '+ip+' "mkdir -p /var/lib/rabbitmq"')
                M = mon()
                M.mount_disk(ip,dev['mq-device'],"/var/lib/rabbitmq")

    def install_set_rabbitMq(self,ip,typeof,hostname):
        os.system('ssh '+ip+' "yum -y install rabbitmq-server"')
        os.system("scp ./config/mq/.erlang.cookie "+ip+":/var/lib/rabbitmq/")
        os.system("scp ./config/mq/rabbitmq.config "+ip+":/etc/rabbitmq/")
        os.system("ssh "+ip+" \"chown rabbitmq:rabbitmq /var/lib/rabbitmq/.erlang.cookie;chmod 400 /var/lib/rabbitmq/.erlang.cookie;systemctl disable rabbitmq-server;rabbitmq-plugins enable rabbitmq_management --offline;rabbitmq-server -detached;\"")
#        os.system("ssh "+ip+" chmod 400 /var/lib/rabbitmq/.erlang.cookie")
#        os.system("ssh "+ip+" rabbitmq-plugins enable rabbitmq_management")
#        rabbitmqctl set_permissions admin '.*' '.*' '.*'
#        os.system("ssh "+ip+" rabbitmq-server -detached")
#        if typeof == "master":
#            os.system("ssh "+ip+" rabbitmqctl set_policy ha-all \"^\"  '{\\\"ha-mode\\\":\\\"all\\\"}'")
#        else:
        if typeof == "slaver":
            order = "\"rabbitmqctl stop_app;rabbitmqctl join_cluster rabbit@"+hostname+";rabbitmqctl start_app\""
            os.system('ssh '+ip+' '+order)
        return

    def operator(self,ips,commonPass):
        hostname = os.popen("ssh "+ips[0]+" hostname").readlines()[0].split("\n")[0].split(".")[0]
        for i in range(len(ips)):
            self.install_set_rabbitMq(ips[i],"master" if i == 0 else "slaver",hostname)
        mqctl = "\"rabbitmqctl add_user iop "+commonPass+";rabbitmqctl set_user_tags iop administrator;rabbitmqctl set_permissions iop '.*' '.*' '.*'\""
        for tip in ips:
            os.system("ssh "+tip+" rabbitmqctl set_vm_memory_high_watermark 0.15")
        os.system("ssh "+ips[0]+" "+mqctl)
        os.system("ssh "+ips[0]+" rabbitmqctl set_policy ha-all \"^\"  '{\\\"ha-mode\\\":\\\"all\\\"}'")
        return



if __name__ == "__main__":
    rabbit = rabbitmq_installer()
    examer = T()
    if not examer.test():
        raise Exception("less arguments or wrong arguments")
    ips = examer.get_ips()
    rabbit.operator(ips)
